package com.alogic.es.xscript.search;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * Query by fuzzy
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsFuzzy extends AbstractLogiclet {
    protected String $field;
    protected String $value;
    protected String $fuzziness;
    protected String $maxExpansions;
    protected String $prefixLength;
    protected String $transPositions;
    protected String $rewrite;

    public EsFuzzy(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $field = PropertiesConstants.getRaw(p,"field",$field);
        $value = PropertiesConstants.getRaw(p,"value",$value);
        $fuzziness = PropertiesConstants.getRaw(p,"fuzziness",$fuzziness);
        $maxExpansions = PropertiesConstants.getRaw(p,"maxExpansions",$maxExpansions);
        $prefixLength = PropertiesConstants.getRaw(p,"prefixLength",$prefixLength);
        $transPositions = PropertiesConstants.getRaw(p,"transPositions",$transPositions);
        $rewrite = PropertiesConstants.getRaw(p,"rewrite",$rewrite);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String field = PropertiesConstants.transform(ctx,$field,"");
        String value = PropertiesConstants.transform(ctx,$value,"");
        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(value)) {
            XsObject query = current.getObjectChild("wildcard", true);
            XsObject f = query.getObjectChild(field,true);
            f.addProperty("value",value);
            f.addProperty("fuzziness", PropertiesConstants.transform(ctx,$fuzziness,""));
            String maxExpansions = PropertiesConstants.transform(ctx,$maxExpansions,"");
            if (StringUtils.isNotEmpty(maxExpansions)){
                f.addProperty("max_expansions", PropertiesConstants.transform(ctx,$maxExpansions,50));
            }
            String prefixLength = PropertiesConstants.transform(ctx,$prefixLength,"");
            if (StringUtils.isNotEmpty(prefixLength)){
                f.addProperty("prefix_length", PropertiesConstants.transform(ctx,$prefixLength,0));
            }
            String transPositions = PropertiesConstants.transform(ctx,$transPositions,"");
            if (StringUtils.isNotEmpty(transPositions)){
                f.addProperty("transpositions", PropertiesConstants.transform(ctx,$transPositions,true));
            }
        }
    }
}